package cn.bjxy.shishaolong.common;

import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.ToDoubleBiFunction;

/**
 * 返回给客户端的响应实体
 *
 * @Author 时少龙
 * @Date 2019-05-25 16:53
 * @Version 2.0
 */
public class ResultMsg extends HashMap<String, Object> {

    public static final String CODE = "code";
    public static final String MSG = "msg";
    public static final String RECORDS = "records";
    public static final String TOTAL = "total";

    //私有化构造方法，不允许通过new创建实例
    private ResultMsg() {
    }

    private ResultMsg(int code, String msg) {
        this.put(CODE, code);
        this.put(MSG, msg);
    }

    private ResultMsg(int code, String msg, Object records) {
        this(code, msg);
        this.put(RECORDS, records);
    }

    private ResultMsg(int code, String msg, Object records, long total) {
        this(code, msg, records);
        this.put(TOTAL, total);
    }

    /**
     * 创建请求响应实体
     *
     * @param code 状态码
     * @param msg  状态信息
     * @return 请求响应实体
     */
    public static ResultMsg create(int code, String msg) {
        return new ResultMsg(code, msg);
    }

    /**
     * 处理成功的响应实体
     *
     * @return
     */
    public static ResultMsg success() {
        return create(StatusCode.SUCCESS, StatusCode.SUCCESS_MSG);
    }

    /**
     * 处理成功的响应实体(带返回数据)
     *
     * @param dataList 数据集合
     * @return 返回的是数组
     */
    public static ResultMsg success(List dataList) {
        return new ResultMsg(StatusCode.SUCCESS, StatusCode.SUCCESS_MSG, dataList, dataList.size());
    }

    /**
     * 处理成功的响应实体(带返回数据)
     *
     * @param data 数据集合
     * @return 返回的是对象
     */
    public static ResultMsg success(Object data) {
        ResultMsg resultMsg = new ResultMsg(StatusCode.SUCCESS, StatusCode.SUCCESS_MSG, data);
        return resultMsg;
    }

    /**
     * 处理成功的响应实体(带返回数据) 和分页
     *
     * @param page 分页查询结果集
     * @return 返回的是数组
     */
    public static ResultMsg success(IPage page) {
        return new ResultMsg(StatusCode.SUCCESS, StatusCode.SUCCESS_MSG, page.getRecords(), page.getTotal());
    }

    public Integer getCode() {
        Object code = this.get(CODE);
        return code != null ? (Integer) code : null;
    }

    public String getMsg() {
        Object msg = this.get(MSG);
        return msg != null ? (String) msg : null;
    }

    public long getTotal() {
        Object total = this.get(TOTAL);
        return total != null ? (long) total : 0;
    }


//    @Override
//    public String toString() {
//        return "ResultMsg{" +
//                "code=" + code +
//                ", msg='" + msg + '\'' +
//                ", records=" + records +
//                ", total=" + total +
//                '}';
//    }
}
